package io.plus.utils.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class ReadWriteLockList<T> extends ReadWriteLockObject<List<T>> {
    private static final long serialVersionUID = 8549668315606224029L;
    private static final Logger log = LoggerFactory.getLogger(ReadWriteLockList.class);

    public ReadWriteLockList(List<T> list) {
        super(list);
    }

    public ReadWriteLockList(List<T> list, ReentrantReadWriteLock lock) {
        super(list, lock);
    }

    public boolean add(T t) {
        WriteLock writeLock = this.getWriteLock();
        writeLock.lock();
        try {
            List<T> list = this.getObject();
            return list.add(t);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
        return false;
    }

    public void clear() {
        WriteLock writeLock = this.getWriteLock();
        writeLock.lock();
        try {
            List<T> list = this.getObject();
            list.clear();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
    }

    public boolean remove(T t) {
        WriteLock writeLock = this.getWriteLock();
        writeLock.lock();
        try {
            List<T> list = this.getObject();
            return list.remove(t);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
        return false;
    }

    public int size() {
        ReadLock readLock = this.getReadLock();
        readLock.lock();
        try {
            List<T> list = this.getObject();
            return list.size();
        } finally {
            readLock.unlock();
        }
    }
}
